var config=require('config.js');
var app={
    /**
     * 存储值
     */
    setData:function(key,value){
        if(typeof value=='object'){
            return wx.setStorageSync(key, JSON.stringify(value));
        }else{
            return wx.setStorageSync(key, value);
        }
    },
    /**
     * 获取存储的值
     */
    getData:function(key,defaultData){
        try{
            var re=wx.getStorageSync(key);
            if(re){
                return JSON.parse(re);
            }else{
                return defaultData;
            }
        }catch(e){
            return re;
        }
    },
    removeData(key){
        wx.removeStorageSync(key);
    },
    setToken:function(token){
        return wx.setStorageSync("token", token);
    },
    getToken:function(){
        return wx.getStorageSync("token");
    },
    removeToken:function(){
        wx.removeStorageSync("token")
    },
    doPost:function(url,data,succCallback,errorCallback){
        app.reqestData(url,data,"POST",succCallback,errorCallback);
    },
    doGet:function(url,data,succCallback,errorCallback){
        var reqParam="";
        for(var key in data){
            reqParam+=key+"="+data[key]+"&";
        }
        reqParam.substr(0,reqParam.length-1);
        app.requestData(url+"?"+reqParam,{},"GET",succCallback,errorCallback);
    },
    requestData:function(url,data,method,succCallback,errorCallback){
        if(data){
            const token=app.getToken();
            if(typeof data=='string'){
                data+=('&token='+token);
            }else{
                let param={
                    token:token
                };
                for(let item in data){
                    let obj=data[item];
                    if(typeof (obj)==='object'){
                        obj=JSON.stringify(obj);
                    }
                    param[item]=obj;
                }
                data=param;
            }
        }
        wx.request({
            url: config.ServerUrl+url,
            data:data,
            method:method,
            header:{
                'content-type':'Application/json'
            },
            success:function(res){
                if(res.data.code==-1){
                    wx.showModal({
                        title: '登录错误',
                        content: '账号登录不稳定，请重新登录',
                        showCancel:false,
                        success:function(res){
                            app.removeToken();
                            app.removeData('admin_nickname');
                            app.removeData('user_type');
                            wx.navigateTo({
                                url: '../pages/login/login',
                            })
                        }
                    })
                }else if(res.data.code>=3){
                    if(!config.debug){
                        res.data.msg="服务器繁忙，请稍后重试";
                    }
                    //弹框提示
                    wx.showModal({
                        title: res.data.msg,
                        showCancel:false,
                        complete:()=>{
                            succCallback(res.data,res.statusCode);
                        }
                    })
                }else{
                    succCallback(res.data,res.statusCode);
                }
            },
            fail:function(res){
                console.log(res);
            },
            complete:function(res){

            }
        })
    },
    /**
     * 微信支付
     * order_id 支付的订单
     * form_id
     */
    pay:function(order_id,form_id){
        return new Promise((resolve,reject)=>{
            app.doPost('/wechatPay/wechatSign',{order_id,form_id},(res)=>{
                if(res.code===1){
                    const timeStamp=new Date().getTime()+"";
                    const options=res.data;
                    options.success=(res)=>{
                        console.log("AddFormId:",res);
                        resolve();
                    };
                    options.fail=(res)=>{
                        console.log("取消支付"+res);
                        reject(res.errMsg);
                    }
                    console.log(options);
                    wx.requestPayment(options);
                }else{
                    wx.showToast({
                        title: res.msg,
                    })
                    console.log(res.msg);
                    reject(res.msg);
                }
            })
        })
    },
    /**
     * 获取access_token
     */
    getaccess_token:(data)=>{
        return new Promise((resolve,reject)=>{
            wx.getUserInfo({
                success:(info)=>{
                    wx.request({
                        url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`,
                        success:(result)=>{
                            let params={
                                access_token:result.data.access_token,
                                touser:info.userInfo
                            };
                            wx.request({
                                url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send',
                                data:params,
                                method:'POST',
                                success:(res)=>{
                                    console.log(res);
                                },
                                fail:(res)=>{

                                }
                            })
                            resolve(result.data);
                        },
                        fail:(res)=>{
                            console.log(res);
                            reject();
                        }
                    })
                }
            })
        })
    },

    /**
     * 获取OpenID
     */
    getOpenId:function(){
        return new Promise((resolve,reject)=>{
            const that=this;
            wx.login({
                success:function(res){
                    app.doPost("/wechatPay/xcxGetOenId",{code:res.code},(result)=>{
                        if(result.code==1){
                            resolve(result.data.openid);
                        }else{
                            reject(result.msg);
                        }
                    })
                },
                fail:function(err){
                    console.log(err);
                }
            })
        })
    }
}
module.exports=app;